/**
 * 请求的拦截处理：
 * 1、加入token
 * 2、补全请求的接口地址
 * 4、返回数据的处理
 * 3、全局的错误判断
 */

import Dialog from "@/native/components/vant/dialog/dialog";
import { API_BASE_URL } from "../config";
import store from "@/store";
import qs from "qs";

// 增加拦截器
Megalo.request.interceptors.before.use(
  options => {
    wx.showNavigationBarLoading();
    // 没有协议的地址统一加上baseUrl
    if (options.url.indexOf("https://") === -1) {
      options.url = API_BASE_URL + options.url;
    }
    if (store.getters.token) {
      if (!options.header) options.header = {};
      options.header["Authorization"] = "Bearer " + store.getters.token;
    }
    return options;
  },
  err => {
    return Promise.reject(err);
  }
);

Megalo.request.interceptors.after.use(
  (response) => {
    wx.hideNavigationBarLoading();
    const { data } = response;
    if (data.code && data.code !== 200) {
      if (data.code === 303) {
        store.dispatch("logout");
        Megalo.redirectTo({
          url: "/pages/index"
        });
        return;
      }

      if (data.code === 304) {
        console.log(response);
        return Promise.reject(response.data);
      }


      Dialog.alert({
        title: "系统错误",
        message: `${JSON.stringify(data)}`,
        confirmButtonText: "重试"
      }).then(() => {
        const pages = getCurrentPages();
        if (pages.length) {
          const currentPage = pages[pages.length - 1];
          const url =
            "/" +
            currentPage.route +
            "?" +
            qs.stringify(currentPage.options, { encode: false });
          console.log("redirect", url, currentPage);
          Megalo.redirectTo({
            url
          });
        }
      });
      return Promise.reject(data.message);
    }

    return data;
  },
  err => {
    wx.hideNavigationBarLoading();
    return Promise.reject(err);
  }
);

export default Megalo.request;
